<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\helpers\traits\ImageUpload;
use app\helpers\traits\SearchDataForModel;
use app\model\AuthRule;
use app\model\Admin as AdminModel;
use app\model\GroupUserPivot;
use app\validate\Admin as ValidateAdmin;
use think\exception\ValidateException;
use think\Request;

class Admin extends BaseController
{
    use ImageUpload, SearchDataForModel;

    /**
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:08
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 用户列表
     */
    public function userList()
    {
        //获取每页显示的条数
        $limit = $this->request->param('limit');
        $map = [];
        if ($this->request->has('username') && !empty($this->request->param('username'))) {
            $map[] = ['username', 'like', '%' . $this->request->param('username') . '%'];
        }
        if ($this->request->has('mobile') && !empty($this->request->param('mobile'))) {
            $map[] = ['mobile', 'like', '%' . $this->request->param('mobile') . '%'];
        }
        $data = AdminModel::with('roles')->where($map)->paginate($limit)->each(function ($item, $key) {
            $pinjie = "";
            foreach ($item['roles'] as $k => $v) {
                $pinjie .= $v['title'] . ',';
            }
            $item['role_name'] = rtrim($pinjie, ',');

        });
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:11
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 更新
     */
    public function userUpdateShow()
    {
        $id = $this->request->param('id');
        $user = AdminModel::find($id);
        if (is_null($user)) {
            return $this->response(404, '此用户不存在');
        }
        // 检查用户权限
        $role_ids = array_column($user->roles()->select()->toArray(),
            'rules');//获取该用户所属角色rules
        if (in_array('*', $role_ids)) {
            $data =
                AuthRule::field('id,name')->where('is_open', AuthRule::OPEN_ONE)
                    ->select()
                    ->toArray();
        } else {
            $data = AuthRule::field('id,name')
                ->where('id', 'in', implode(',', $role_ids))
                ->where('is_open', AuthRule::OPEN_ONE)
                ->select()->toArray();
        }
        $url = [];
        foreach ($data as $key => $v) {
            $url[] = $v['name'];
        }
        $user['url'] = implode(',', $url);
        return $this->response($user->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:11
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 用户新增or编辑
     */
    public function userSave()
    {

        $id = $this->request->param('id', 0);
        try {
            $validator = $this->validate($this->request->param(),
                ValidateAdmin::rules($id),
                ValidateAdmin::msg());
            if ($validator) {
                $data = $this->request->except(['password_confirm']);
                if (intval($id) === 0) {
                    $data['password'] = password_hash(!empty($data['password']) ? $data['password'] : '111111', PASSWORD_DEFAULT);
                    $data['create_id'] = $this->request->uid ?? 0;
                    $user = AdminModel::create($data);
                } else {
                    if (empty($data['password'])) {
                        unset($data['password']);
                    } else {
                        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                    }
                    $user = AdminModel::find($id);
                    $user->update($data);
                }

                //添加用户角色中间表信息
                //GroupUserPivot::roleUserSave($user,$this->request->param('role_id'));
                return $this->response();
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->response(403, $e->getError());
        }
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:13
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除用户
     */
    public function userDelete($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            if (intval($id) === 1) {
                return $this->response(403, '超级管理员,不能删除');
            }
            $user = AdminModel::find($id);
            if (is_null($user)) {
                return $this->response(404, '此用户不存在');
            }
            //->force()
            $user->delete();
        }
        return $this->response();
    }

}
